<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'db.php';

try {
    // 获取参数
    $booking_id = isset($_POST['booking_id']) ? intval($_POST['booking_id']) : 0;
    $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;

    if (!$booking_id || !$user_id) {
        throw new Exception('参数错误');
    }

    // 开始事务
    $conn->begin_transaction();

    try {
        // 获取预约信息，同时验证用户权限
        $sql = "SELECT * FROM bookings WHERE id = ? AND user_id = ? AND status < 2";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $booking_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            throw new Exception('预约不存在或无法取消');
        }

        $booking = $result->fetch_assoc();

        // 更新预约状态
        $update_sql = "UPDATE bookings SET status = 3 WHERE id = ? AND user_id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ii", $booking_id, $user_id);
        
        if (!$update_stmt->execute()) {
            throw new Exception('取消预约失败');
        }

        // 如果是私教课程，恢复教练排班表的时间段
        if ($booking['type'] == 1) {
            $schedule_sql = "UPDATE coach_schedules 
                           SET is_available = 1 
                           WHERE coach_id = ? 
                           AND date = ? 
                           AND time_slot = ?";
            $schedule_stmt = $conn->prepare($schedule_sql);
            $schedule_stmt->bind_param("iss", 
                $booking['coach_id'], 
                $booking['booking_date'], 
                $booking['time_slot']
            );
            
            if (!$schedule_stmt->execute()) {
                throw new Exception('恢复教练排班失败');
            }
        }
        // 如果是团课，更新课程已预约人数
        else if ($booking['type'] == 2) {
            $course_sql = "UPDATE courses SET booked_count = booked_count - 1 
                          WHERE id = ? AND booked_count > 0";
            $course_stmt = $conn->prepare($course_sql);
            $course_stmt->bind_param("i", $booking['course_id']);
            
            if (!$course_stmt->execute()) {
                throw new Exception('更新课程预约人数失败');
            }
        }

        // 提交事务
        $conn->commit();
        
        echo json_encode([
            'status' => 'success',
            'message' => '取消成功'
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    if (isset($update_stmt)) $update_stmt->close();
    if (isset($schedule_stmt)) $schedule_stmt->close();
    if (isset($course_stmt)) $course_stmt->close();
    if (isset($conn)) $conn->close();
}
?> 